package com.hsy.swu.widget

import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.widget.Toast
import androidx.room.Room
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hsy.swu.clouddb.MyUser
import com.hsy.swu.home.course.CourseModel
import com.hsy.swu.home.course.SimpleCourseModel
import com.hsy.swu.hsyutils.fileDelete
import com.hsy.swu.hsyutils.fileRead
import com.hsy.swu.hsyutils.fileWrite
import com.hsy.swu.roomdb.AppDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

class CourseWidget : AppWidgetProvider() {
    override fun onEnabled(context: Context?) {
        super.onEnabled(context)
        context?.let { Toast.makeText(it, "课程提醒组件已添加到桌面", Toast.LENGTH_SHORT).show() }
        context?.writeCourse()
    }

    override fun onDisabled(context: Context?) {
        super.onDisabled(context)
        context?.fileDelete("simpleCourseModelList.json")
    }

    override fun onUpdate(
        context: Context?,
        appWidgetManager: AppWidgetManager?,
        appWidgetIds: IntArray?
    ) {
        super.onUpdate(context, appWidgetManager, appWidgetIds)
        if (context != null) {
            val allCourseList = context.readCourse()
            context.updateCourseWidget(SimpleCourseModel.getShowOnWidgetList(allCourseList))
            SimpleCourseModel.getSoonBeginCourse(allCourseList)
                ?.let { context.postCourseNotification(it) }
        }
    }

    /** 从数据库中取并写入文件 */
    private fun Context.writeCourse() {
        val courseDao = Room.databaseBuilder(
            this, AppDatabase::class.java, "swu"
        ).build().courseDao()
        val courseList: List<CourseModel>
        runBlocking {
            withContext(Dispatchers.IO) {
                courseList = courseDao.getAllByAccount(MyUser.currentUser.account)
            }
        }
        updateSimpleCourseModelFile(courseList)
    }

    /** 从文件中读取 */
    private fun Context.readCourse(): List<SimpleCourseModel> {
        return Gson().fromJson(
            fileRead("simpleCourseModelList.json"),
            object : TypeToken<List<SimpleCourseModel>>() {}.type
        )
    }
}